/*
* @Author: zhangsai
* @Date: 2018/4/11
* @description: 选择标签组件
*/
<template>
    <div>
        <el-form :model="form" :rules="rules" ref="tagForm">
            <el-form-item label="标签" label-width="90px">
                <el-row :gutter="5">
                    <el-col :span="7">
                        <el-select v-model="tagType"
                            @change="tagTypeChange"
                            placeholder="请选择">
                            <el-option
                                v-for="(tag) in dropDown.tagType"
                                :key="tag.dictValue"
                                :label="tag.dictName"
                                :value="tag.dictValue"
                            >
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="16" v-if="tagType == 1" class="pull-right">
                        <el-cascader
                            style="width:100%"
                            @change="changeCvIndustryTag"
                            v-model="cvIndustryValueTag"
                            :options="cvIndustryListCascader"
                            :filterable="true"
                            :clearable="true" />
                    </el-col>
                </el-row>
            </el-form-item>    
            <el-form-item label="" label-width="90px">    
                <el-row>    
                    <el-select v-model="tagValue"
                        @change="changeTags"
                        style="width:100%"
                        multiple
                        placeholder="请选择">
                        <el-option
                            v-for="(tag) in dropDownTagsList"
                            :key="tag.id"
                            :label="tag.tagsName"
                            :value="tag.id"
                        >
                        </el-option>
                    </el-select>
                </el-row>
            </el-form-item>
            <el-form-item v-if="shouwAddTag" label="关键字" label-width="90px">
                <el-row >
                    <el-col :span="18">
                        <el-input placeholder="请输入关键字" v-model="addTagVal" />
                    </el-col>
                    <el-col :span="6" class="align-right">
                        <el-button type="primary" @click="addTag">添加</el-button>
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item :label="title" prop="tagList" :title="comTagDtoList" label-width="90px">
                <el-row class="ca-box minheight tagBox">
                    <select v-model="form.tagList" style="display:none;"></select>
                    <el-tag
                        class="m-r-5"
                        v-for="(tag,index) in comTagListD"
                        :key="index"
                        closable
                        :type="handleTagType(tag)"
                        @close="handleTagClose(index)">
                            <span @click="setTagStatus(tag, index)">
                                {{tag.tagName}}
                                <span v-if="tag.dataCount">{{tag.dataCount}}</span>
                            </span>    
                    </el-tag>
                </el-row>
            </el-form-item> 
        </el-form>
        <!--是否在cvs显示弹框-->
        <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="30%"
        >
            <span>{{dialogTip}}</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitSetTagShowStatus">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import Vue from 'vue';
import { Component, Prop, Watch } from 'vue-property-decorator';
import { TagsVo, ComTagDto } from '../../api/Interface';
import { getCascaderData, getListByChildren } from '../../libs/utils';
import CommonService from '../../service/common';
@Component
export default class Tag extends Vue {
    @Prop({ default: '投资标签' })
    public title: string;  // 标签列表
    @Prop({ default: [] })
    public comTagDtoList: ComTagDto[];  // 标签列表
    @Prop({ default: [] })
    public cvIndustryValue: string[];  // cv行业联动
    @Prop({ default: false})
    public shouwAddTag: boolean; // 是否显示添加关键字
    @Prop()
    public businessId: number; // 业务Id
    @Prop()
    public businessType: number; // 业务类型
    // 初始化数据 相当于data
    public dropDown: object = {
        tagType: this.$store.state.user.dictionary.dicList.tagType, // 标签列表
        tagsList: [],
    };
    // cv行业
    public cvIndustryList = this.$store.state.user.dictionary.cvIndustryList;
    public cvIndustryListCascader = getCascaderData( {data: this.cvIndustryList} );
    public cvIndustryOneList = getListByChildren(this.cvIndustryList);
    // 弹框相关 
    public dialogVisible: boolean = false;
    public dialogTip: string = '请确定展示';
    public activeIndustryNumber: number = 0;
    // 弹框相关 end
    // 标签类型
    public tagType: string = '';
    // 标签id集合
    public tagValue: number[] = [];
    // 标签-行业
    public cvIndustryValueTag: string[] = [];
    // 标签下拉  list
    public dropDownTagsList: TagsVo[] = [];
    // tags列表
    public tagsList: string[] = [];
    // 选中标签池 （隐藏）
    public tagsListHidden: number[][] = [[], [], [], []];
    public tagsListHiddenObj: { tagsName: string; id: number, tagsType: number}[][] = [[], [], [], []];
    public rules = {
        tagList: [
            { required: true, validator: this.validateIndustryTag, message: '请选择投资标签', trigger: 'change' }
        ]
    };
    public comTagListD: ComTagDto[] = [];
    public form = { tagList: this.comTagListD };
    public addTagVal: string = '';
    // refs
    public $refs: {
        tagForm: HTMLFormElement
    };

    // watch
    @Watch('comTagDtoList')
    public onChange() {
        this.comTagListD = this.comTagDtoList;
        this.comTagListD.map(item => {
            if (item.tagsType) {
                this.tagsListHidden[item.tagsType - 1].push(item.tagId);
                this.tagsListHiddenObj[item.tagsType - 1].push( {tagsName: item.tagName, id: item.tagId, tagsType: item.tagsType} );
            }
        });
    }
    @Watch('cvIndustryValue')
    public onChangeCvIndustryValue() {
        this.cvIndustryValueTag = this.cvIndustryValue;
    }
    @Watch('comTagListD')
    public onChangecomTagListD() {
        if (this.comTagListD.length > 0) {
            this.$emit('tagPass', true);
        } else {
            this.$emit('tagPass', false);
        }
    }


    // 生命周期
    // 声明周期钩子
    public mounted() {
        this.comTagListD = this.comTagDtoList;
    }
    // 方法
    public addTag() {
        const tag: ComTagDto = {} as ComTagDto;
        tag.tagName = this.addTagVal;
        tag.companyId = Number(this.$route.params.itemId);
        tag.operateType = 1;
        tag.businessId = this.businessId; // 业务id
        tag.businessType = this.businessType; // 业务类型
        tag.tagsType = 4;
        this.comTagListD.push(tag);
    
    }
    // 计算标签颜色
    public handleTagType(tag: ComTagDto) {
        let type = tag.operateType === 1 ? '' : 'info';
        // 是否cvs显示1是2否
        type = tag.showStatus === 1 ? 'success' : type;
        return type;
    }
    // 弹框 设置标签是否在cvs显示
    public setTagStatus(tag: ComTagDto, index: number) {
        if (this.title === '投资标签') {
            const status = tag.showStatus;
            if (status === 1) {
                this.dialogTip = '请确定不展示' + tag.tagName + (tag.dataCount ? tag.dataCount : '') + '?';
            } else {
                this.dialogTip = '请确定展示' + tag.tagName + (tag.dataCount ? tag.dataCount : '') + '?';
            }
            this.activeIndustryNumber = index;
            this.dialogVisible = true;
        }
        
    }
    // 设置标签是否在cvs显示
    public submitSetTagShowStatus() {
        const tag: ComTagDto = this.comTagListD[this.activeIndustryNumber];
        tag.showStatus = tag.showStatus === 1 ? 2 : 1;
        this.dialogVisible = false;
    }
    // 删除关注行业
    public handleTagClose(index: number) {
        this.comTagListD.splice(index, 1);
    }
    // 标签类型change
    public async tagTypeChange(tag: string) {
        this.cvIndustryValueTag = this.cvIndustryValue;
        const lastIndustry: string = this.cvIndustryValueTag[this.cvIndustryValueTag.length - 1];
        if (tag === '1' && lastIndustry) {
            const obj = this.cvIndustryOneList.find(x => x.code === lastIndustry);
            const tagList: TagsVo[] = await CommonService.getTagsByIndustryId(obj.id);
            this.dropDownTagsList = tagList;
        } else {
            const params = {
                tagType: tag
            };
            const res = await CommonService.getTagListByType(params);
            this.dropDownTagsList = res.data;
        }
        this.tagValue = this.tagsListHidden[Number(tag) - 1];
    }
    // 标签change
    public async changeTags(tag: string[]) {
        if (tag.length && tag.length > 0) {
            const key = Number(this.tagType) - 1;
            const tagList: TagsVo[] = [];
            tag.map(item => {
                const t: TagsVo = {} as TagsVo;
                const findTag: any = this.dropDownTagsList.find(x => x.id === Number(item));
                if (findTag) {
                    t.tagsName = findTag.tagsName;
                    t.id = findTag.id;
                    t.tagsType = findTag.tagsType;
                    tagList.push(t);
                }
            });
            this.tagsListHidden[key] = tag.map(item => {
                return Number(item);
            });
            this.tagsListHiddenObj[key] = tagList;
        } else {
            const key = Number(this.tagType) - 1;
            this.tagsListHidden[key] = [];
            this.tagsListHiddenObj[key] = [];
        }
        this.comTagDtoListFunc();
    }
    // 行业选择 获取 行业下的标签
    public async changeCvIndustryTag(value: string[]) {
        const lastIndustry: string = value[value.length - 1];
        if (lastIndustry) {
            const obj = this.cvIndustryOneList.find(x => x.code === lastIndustry);
            const tagList: TagsVo[] = await CommonService.getTagsByIndustryId(obj.id);
            this.dropDownTagsList = tagList;
        }
    }
    // 生成 ComTagDto
    public comTagDtoListFunc() {
        const comTagDtoList: ComTagDto[] = [];
        this.tagsListHiddenObj.map((item: TagsVo[], i: number) => {
            item.map((o: TagsVo, j: number) => {
                const comTag: ComTagDto = {} as ComTagDto;
                comTag.companyId = Number(this.$route.params.itemId);
                comTag.tagId = o.id;
                comTag.tagName = o.tagsName;
                comTag.operateType = 1;
                comTag.tagsType = o.tagsType;
                comTagDtoList.push(comTag);
            });
        });
        this.comTagListD = comTagDtoList;
        this.$refs.tagForm.validate();
    }
    // 验证
    public validateIndustryTag(rule: object, value: string[], callback: (obj ?: object) => void) {
        if (this.comTagListD && this.comTagListD.length > 0) {
            callback();
        } else {
            callback(new Error('请选择投资标签'));
        }
    }
    // 验证是否必填
    public checkInput() {
        return new Promise((resolve, reject) => {
            if (this.comTagListD.length > 0) {
                resolve(true);
                this.$emit('pass');
            } else {
                this.$refs.tagForm.validate((valid) => {
                    resolve(valid);
                }, (err) => {
                    reject(false);
                });
            }
        });
    }
    public getTagList() {
        return new Promise((resolve, reject) => {
            resolve(this.comTagListD);
        });
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.minheight{
  height: 150px;
  overflow-y: auto;
  padding: 0 10px;
  border-radius: 5px;
}
.ca-box {
    background: #fff;
    border: #dbe3ea 1px solid;
}
</style>